package com.colbby.datahouse.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.colbby.datahouse.utils.IOUtils;
import com.taobao.api.internal.util.StringUtils;

public class ConnectionContext {

	private ThreadLocal<Connection> local = new ThreadLocal<>();
	
	private String url;
	private String user;
	private String password;
	
	private static final Object sync = new Object();
	
	public ConnectionContext(String driverPath) {
		synchronized(sync) {
//			String drivers = System.getProperty("jdbc.driver");
//			if(StringUtils.isEmpty(drivers)) {
//				System.setProperty("jdbc.driver", driverPath);
//			} else {
//				System.setProperty("jdbc.driver", drivers + ":" + driverPath);
//			}
			try {
				Class.forName(driverPath);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public boolean hasConnection() {
		return local.get() != null;
	}
	
	public Connection get() {
		if(local.get() == null) {
			try {
				local.set(DriverManager.getConnection(url, user, password));
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		return local.get();
	}
	
	public void remove() {
		Connection conn = local.get();
		IOUtils.close(conn);
		local.remove();
	}
	
	public ConnectionContext setUrl(String url) {
		this.url = url;
		return this;
	}

	public ConnectionContext setUser(String user) {
		this.user = user;
		return this;
	}

	public ConnectionContext setPassword(String password) {
		this.password = password;
		return this;
	}
}
